﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Singer.BackgroundJob.RabbitMQ;
using Singer.BackgroundJob.RabbitMQ.BackgroundJobLogs;
using Singer.BackgroundJob.RabbitMQ.Contracts;
using Singer.Shared.UserContext;
using Singer.UnitTestWeb.BackgroundJobs.JobArgs;

namespace Singer.UintTestBackgroundJob.JobExecutors;

[BackgroundJobExecutor(typeof(BookJobArgs), "Book测试任务", FailRetry = true, MaxRetryCount = 3)]
public class BookJobExecutor : BackgroundJobExecutorBase<BookJobArgs>
{
    private readonly ILogger<BookJobExecutor> _logger;
    private readonly IUserContextAccessor _userContextAccessor;
    public BookJobExecutor(
        ILogger<BookJobExecutor> logger,
        IUserContextAccessor userContextAccessor,
        BackgroundJobLogManager backgroundJobLogManager) : base(backgroundJobLogManager)
    {
        _logger = logger;
        _userContextAccessor = userContextAccessor;
    }

    public override async Task ExecuteAsync()
    {
        _logger.LogInformation($"【{nameof(BookJobExecutor)}】触发，" +
            $"【JobArgs】：'{JobLog.Args}'；" +
            $"【UserContext】：'{JsonConvert.SerializeObject(_userContextAccessor.UserContext)}'。");
        int testErrorRandom = Random.Shared.Next(5, 10);
        var testErrorList = new int[] { 3, 5, 7 };
        for (int i = 1; i <= 30; i++)
        {
            if (StoppingCts.IsCancellationRequested) // 任务取消时，跳出循环
                break;
            if (testErrorRandom == i)
                throw new Exception("测试异常，终止任务");
            if (testErrorList.Contains(i))
            {
                await LogErrorAsync($"测试异常日志 '{i}' ");
                continue;
            }
            Console.WriteLine($"任务执行中...{i}");
            await LogInfoAsync($"任务执行中...{i}");
            await Task.Delay(1000);
        }
    }
}
